#include "tbox.h"
#include <stdlib.h>
#include <string.h>

enum directions {
    LEFT = 0,
    TOP,
    RIGHT,
    BOTTOM,
    INNER,
};

tbox_button_t *msg;

int app_exit(tbox_widget_t *wi, tbox_event_t *ev) {
    (void)wi;
    if (ev->ev == TBOX_EVENT_MOUSE_DOWN) {
        wi->fg = 0xbf1d2d;
    }

    if (ev->ev == TBOX_EVENT_MOUSE_UP || ev->ev == TBOX_EVENT_MOUSE_MOVEOUT) {
        wi->fg = 0x0; // default
    }

    if (ev->ev == TBOX_EVENT_MOUSE_CLICK) {
        tbox_exit();
    }

    return 0;
}

char *evname[] = {
    "null",
    "click",
    "dn",
    "up",
    "mi",
    "mo",
    "key-up",
    "key-dn",
};

int count = 0;

int on_click(tbox_widget_t *wi, tbox_event_t *ev) {
    char buf[128];

    if (ev->ev == TBOX_EVENT_MOUSE_MOVEIN) {
        wi->fg = 0xb8f1ed; // blue
    }
    if (ev->ev == TBOX_EVENT_MOUSE_MOVEOUT) {
        wi->fg = 0xf3d751; // yellow
    }
    if (ev->ev == TBOX_EVENT_MOUSE_DOWN) {
        wi->fg = 0xddff95; // green
    }
    if (ev->ev == TBOX_EVENT_MOUSE_UP) {
        wi->fg = 0x0; // default
    }

    sprintf(buf, "%s (%d, %d): ", wi->_data.text, wi->x, wi->y);
    sprintf(buf + strlen(buf), " +%d key=ffff-%d, x=%d, y=%d, ev=%s", count++, 0xffff - ev->key,
        ev->x, ev->y, evname[ev->ev]);
    // msg->set_text(msg, buf);

    return 0;
}

int main() {
    struct tbox_conf conf = {.loglevel = TBOX_LOG_INFO, .logfile = "x.log"};

    tbox_init(&conf);

    tbox_button_t *root = tbox_button(8, 3, "EXIT");
    msg = tbox_button(64, 3, "message");

    tbox_button_t *btn0 = tbox_button(16, 3, "button 0");
    tbox_button_t *btn1 = tbox_button(16, 3, "button 1");
    tbox_button_t *btn2 = tbox_button(16, 3, "button 2");
    tbox_button_t *btn3 = tbox_button(16, 3, "button 3");

    // mouse event
    root->on_mouse = app_exit;
    btn0->on_mouse = on_click;
    btn1->on_mouse = on_click;
    btn2->on_mouse = on_click;
    btn3->on_mouse = on_click;

    // layout
    tbox_layout_add(root); // TODO: remove this
    root->layout[BOTTOM] = msg;
    msg->margin[TOP] = 20;

    root->layout[RIGHT] = btn0;
    btn0->layout[RIGHT] = btn1;
    btn0->layout[BOTTOM] = btn2;
    btn1->layout[BOTTOM] = btn3;

    btn0->margin[TOP] = 2;
    btn0->margin[LEFT] = 3;
    btn1->margin[LEFT] = 3;
    btn2->margin[TOP] = 2;
    btn3->margin[TOP] = 2;

    root->align = TBOX_ALIGN_CENTER;
    root->text_wrap = false;
    // root->fg = 0xbf1d2d;

    return tbox_poll();
}
